package org.yang.loginunion.core.wx.miniappmobile;

import org.apache.commons.lang3.StringUtils;
import org.yang.loginunion.core.LoginClient;
import org.yang.loginunion.core.constants.IdentityType;
import org.yang.loginunion.core.exception.LoginException;
import org.yang.loginunion.core.repository.OauthRepository;
import org.yang.loginunion.core.wx.miniappmobile.request.IMaMobileRequest;

/**
 * 微信小程序中本机手机号登录
 * @author Billyang
 * @date 2024/8/9 18:15
 */
public class WeixinMiniappMobileClient implements LoginClient {

    private OauthRepository oauthRepository;
    private IMaMobileRequest maMobileRequest;

    public WeixinMiniappMobileClient(OauthRepository oauthRepository, IMaMobileRequest maMobileRequest) {
        this.oauthRepository = oauthRepository;
        this.maMobileRequest = maMobileRequest;
    }

    @Override
    public String login(String ignore1, String ignore2, String code) {
        if (StringUtils.isBlank(code)) {
            throw new LoginException("缺失参数");
        }

        String mobile = maMobileRequest.getMobile(code);

        String userId = oauthRepository.getUserId(IdentityType.MOBILE, mobile);
        if (userId == null) {// 账号不存在
            // 创建新用户
            userId = oauthRepository.registerUser(IdentityType.MOBILE, mobile);
        }
        return userId;
    }
}
